from flask import Flask, render_template, url_for
from src.weather_spider import WeatherSpider
from src.regression import Regression
from src.config import *
from src.AipSpeech import client
import random

app = Flask(__name__)


# 初始页面
@app.route('/')
def index():
    return '<h1>Welcome to Weather Forecast System</h1>'


# 爬取所有城市
@app.route('/crawl/all')
def crawl_all():
    ws = WeatherSpider()
    ws.crawl_all()
    return '已爬取完成所有城市'


# 爬取对应城市
@app.route('/crawl/<city>')
def crawl_city(city):
    ws = WeatherSpider()
    ws.crawl_city(city)
    return '已爬取{}的天气'.format(city)


# 训练对应城市模型
@app.route('/train/<city>')
def train(city):
    r = Regression()
    r.train(city)
    return '已训练好了{}的天气模型'.format(city)


# 预测对应城市天气
@app.route('/forecast/<city>/<int:year>/<int:month>/<int:day>')
def forecast(city, year, month, day):
    r = Regression()
    top, low, weather = r.predict(city, month, day)
    text = '{}{}年{}月{}日的天气是{},最高{}度最低{}度'.format(city, year, month, day, weather, top, low)
    result = client.synthesis(text, 'zh', 1,
                              {
                                  'vol': 5,
                              })
    file_name = "auido/" + city + str(round(random.random() * 1000000)) + ".mp3"
    if not isinstance(result, dict):
        with open("static/" + file_name, 'wb') as f:
            f.write(result)
        return render_template("play.html", url=url_for("static", filename=file_name), text=text)
    else:
        return "语音合成出现错误"


if __name__ == '__main__':
    app.run(host=API_HOST, port=API_PORT)
